package com.ruoyi.project.monitor.job.task;

import java.io.IOException;
import java.util.List;

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ElasticSearchUtils;
import com.ruoyi.common.utils.JsonBeanUtil;
import com.ruoyi.project.shortUrl.cache.ShortCodeCache;
import com.ruoyi.project.shortUrl.cache.ShortCodeCacheEntity;
import com.ruoyi.project.shortUrl.url.domain.ShortUrl;
import com.ruoyi.project.shortUrl.url.service.IShortUrlService;

/**
 * 定时任务调度测试
 * 
 * @author ruoyi
 */
@Component("shortUrlTask")
public class ShortUrlTask
{
	@Autowired
	private IShortUrlService shortUrlService;
	
    public void delExpire()
    {
        String nowDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.getNowDate());
        shortUrlService.deleteShortUrlByIExpireDate(nowDay);
    }

    public void syncAll()
    {
    	try {
			ElasticSearchUtils.clearIndex(ShortCodeCache.index);
		} catch (Exception e) {
			if(e instanceof ElasticsearchStatusException) {
				String errorMsg = ((ElasticsearchStatusException)e).getDetailedMessage();
				if(errorMsg.contains("no such index")) {
					String mapping = "{\"properties\":{\"expirationTime\":{\"type\":\"keyword\"},\"shortCode\":{\"type\":\"keyword\"},\"targetUrl\":{\"type\":\"keyword\"},\"createUserId\":{\"type\":\"keyword\"}}}";
					try {
						ElasticSearchUtils.createIndex(ShortCodeCache.index, mapping);
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
		int total = shortUrlService.countAll();
		if(total>0) {
			int pageSize = 1000;
			int pages = total/1000 + total%1000==0?0:1;
			
			for(int i=1; i<=pages; i++) {
				PageHelper.startPage(i, pageSize);
				List<ShortUrl> list = shortUrlService.selectShortUrlList(null);
				
				BulkRequest bulkRequest = new BulkRequest();
		        //超时时间设长点，30分钟
		        bulkRequest.timeout(TimeValue.timeValueMinutes(30L));
				for(ShortUrl shortUrl:list) {
					IndexRequest request = new IndexRequest(ShortCodeCache.index); 
					request.id(shortUrl.getShortCode()); 
					ShortCodeCacheEntity cacheEntity = new ShortCodeCacheEntity(shortUrl);
		    		request.source(JsonBeanUtil.transBean2Json(cacheEntity), XContentType.JSON);
		    		bulkRequest.add(request);
				}
				ElasticSearchUtils.bulkAdd(bulkRequest);
			}
		}
    }
}
